import React, { useState, useEffect, useRef } from 'react';
import { Layout, Menu, Avatar, Dropdown } from 'antd';
import {
  HomeOutlined,
  VideoCameraOutlined,
  MessageOutlined,
  SettingOutlined,
  UserOutlined,
  LogoutOutlined,
  BookOutlined,
} from '@ant-design/icons';
import { Routes, Route, useNavigate, useLocation } from 'react-router-dom';
import Dashboard from '../Pages/Dashboard';
import MovieListByType from '../MovieRecommend/MovieListByType';
import MovieRecommendationNav from '../MovieRecommend/MovieRecommendationNav';
import MovieDetail from '../MovieRecommend/MovieDetail';
import PersonalizedRecommendation from '../PersonalizedRecommendation/PersonalizedRecommendation';
import ChatBot from '../ChatBot/ChatBot';
import Settings from '../Settings/Settings';
import UserGuide from '../UserGuide/UserGuide';
import authService from '../../services/AuthService';
import '../../styles/MainLayout.css';

const { Sider, Content } = Layout;

const MainLayout = ({ onLogout }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const navigate = useNavigate();
  const location = useLocation();

  // 新增粒子背景相关逻辑
  const particleContainerRef = useRef(null);
  
  useEffect(() => {
    const container = particleContainerRef.current;
    if (!container) return;
    
    // 创建粒子
    const createParticles = () => {
      const particleCount = 50;
      
      for (let i = 0; i < particleCount; i++) {
        const particle = document.createElement('div');
        particle.className = 'particle';
        
        // 随机属性
        const size = Math.random() * 15 + 5;
        const posX = Math.random() * 100;
        const posY = Math.random() * 100;
        const animationDuration = Math.random() * 20 + 10;
        const animationDelay = Math.random() * 0.3;
        const hue = Math.floor(Math.random() * 360);
        
        particle.style.width = `${size}px`;
        particle.style.height = `${size}px`;
        particle.style.left = `${posX}%`;
        particle.style.top = `${posY}%`;
        particle.style.animationDuration = `${animationDuration}s`;
        particle.style.animationDelay = `${animationDelay}s`;
        particle.style.background = `hsla(${hue}, 100%, 70%, ${Math.random() * 0.5 + 0.3})`;
        
        container.appendChild(particle);
      }
    };
    
    createParticles();
    
    // 清理函数
    return () => {
      while (container.firstChild) {
        container.removeChild(container.firstChild);
      }
    };
  }, []);

  // 获取当前用户信息
  useEffect(() => {
    const fetchCurrentUser = async () => {
      try {
        const result = await authService.getCurrentUser();
        if (result.success) {
          setCurrentUser(result.user);
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };

    fetchCurrentUser();
  }, []);

  const menuItems = [
    {
      key: '/',
      icon: <HomeOutlined className="icon-home"/>,
      label: '首页',
    },
    {
      key: '/recommendation',
      icon: <VideoCameraOutlined className="icon-blue"/>,
      label: '电影推荐',
    },
    {
      key: '/chat',
      icon: <MessageOutlined className="icon-green"/>,
      label: '智能对话',
    },
    {
      key: '/guide',
      icon: <BookOutlined className="icon-orange"/>,
      label: '使用指南',
    },
    {
      key: '/settings',
      icon: <SettingOutlined className="icon-purple"/>,
      label: '设置',
    },
  ];

  const handleMenuClick = ({ key }) => {
    navigate(key);
  };

  const handleUserMenuClick = ({ key }) => {
    if (key === 'profile') {
      navigate('/settings');
    } else if (key === 'logout') {
      onLogout();
    }
  };

  const userMenuItems = [
    {
      key: 'profile',
      icon: <UserOutlined />,
      label: '个人资料',
    },
    {
      key: 'logout',
      icon: <LogoutOutlined />,
      label: '退出登录',
    },
  ];

  return (
    <Layout className="main-layout">
      <Sider 
        trigger={null} 
        className="main-sider"
        width={250}
      >
        <div className="logo">
          <div className="logo-icon">🎬</div>
          <div className="logo-text">
            <h2>CineMind AI</h2>
            <p>智能电影推荐</p>
          </div>
        </div>
        
        <Menu
          theme="light"
          mode="vertical"
          selectedKeys={[location.pathname]}
          items={menuItems}
          onClick={handleMenuClick}
          className="main-menu"
        />

        <div className="user-info-container">
          <Dropdown
            menu={{ items: userMenuItems, onClick: handleUserMenuClick }}
            placement="bottomRight"
            arrow
            overlayClassName="user-dropdown"
          >
            <div className="user-info">
              <Avatar icon={<UserOutlined />} />
              <span className="username">{currentUser?.nickname || '用户'}</span>
            </div>
          </Dropdown>
        </div>
      </Sider>
      
      <Layout className="site-layout">
        {/* 新增粒子背景容器 */}
        <div className="particle-background" ref={particleContainerRef}></div>
        <Content className="site-layout-content">
            <Routes>
              <Route path="/" element={<Dashboard />} />
              <Route path="/recommendation" element={<div><MovieRecommendationNav /></div>} />
              <Route path="/recommendation/upcoming" element={<MovieListByType type="upcoming" />} />
              <Route path="/recommendation/now-playing" element={<MovieListByType type="now-playing" />} />
              <Route path="/recommendation/personalized" element={<PersonalizedRecommendation />} />
              <Route path="/recommendation/movie-detail/:movieId" element={<MovieDetail />} />
              <Route path="/chat" element={<ChatBot />} />
              <Route path="/guide" element={<UserGuide />} />
              <Route path="/settings" element={<Settings />} />
            </Routes>
        </Content>
      </Layout>
    </Layout>
  );
};

export default MainLayout;